<template>
  <div class="scan-task-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>扫描任务管理</h2>
      <p>创建和管理扫描任务</p>
    </div>

    <!-- 任务创建表单 -->
    <el-card class="form-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>{{ isEdit ? "编辑任务" : "创建扫描任务" }}</span>
          <div class="card-actions">
            <el-button v-if="isEdit" size="small" @click="cancelEdit">
              取消编辑
            </el-button>
            <el-button type="primary" size="small" @click="handleSubmit">
              {{ isEdit ? "更新任务" : "创建任务" }}
            </el-button>
          </div>
        </div>
      </template>

      <DynamicForm
        ref="formRef"
        v-model="formData"
        :form-config="formConfig"
        :gutter="24"
        label-width="120px"
      />
    </el-card>

    <!-- 任务列表表格 -->
    <el-card class="table-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>扫描任务列表</span>
          <div class="card-actions">
            <el-button
              size="small"
              @click="refreshTable"
              :loading="tableLoading"
            >
              刷新
            </el-button>
          </div>
        </div>
      </template>

      <DynamicTable
        ref="tableRef"
        :data="tableData"
        :columns="tableColumns"
        :loading="tableLoading"
        :pagination="pagination"
        selection-type="multiple"
        @selection-change="handleSelectionChange"
        @current-page-change="handlePageChange"
        @size-change="handleSizeChange"
      >
        <!-- 操作列插槽 -->
        <template #action="{ row }">
          <el-button type="primary" size="small" link @click="handleEdit(row)">
            编辑
          </el-button>
          <el-button
            type="success"
            size="small"
            link
            @click="handleExecute(row)"
            :disabled="row.status === 'running'"
          >
            {{ row.status === "running" ? "运行中" : "执行" }}
          </el-button>
          <el-button
            type="danger"
            size="small"
            link
            @click="handleDelete(row)"
            :disabled="row.status === 'running'"
          >
            删除
          </el-button>
        </template>

        <!-- 状态列插槽 -->
        <template #status="{ row }">
          <el-tag :type="getStatusTagType(row.status)" size="small">
            {{ getStatusText(row.status) }}
          </el-tag>
        </template>

        <!-- 扫描类型列插槽 -->
        <template #scanType="{ row }">
          <el-tag size="small" effect="plain">
            {{ getScanTypeText(row.scanType) }}
          </el-tag>
        </template>

        <!-- 进度列插槽 -->
        <template #progress="{ row }">
          <el-progress
            :percentage="row.progress || 0"
            :status="
              row.status === 'completed'
                ? 'success'
                : row.status === 'failed'
                ? 'exception'
                : row.status === 'running'
                ? ''
                : 'warning'
            "
            :stroke-width="6"
            text-inside
          />
        </template>

        <!-- 工具栏右侧插槽 -->
        <template #toolbar-right>
          <el-button
            type="danger"
            size="small"
            :disabled="selectedRows.length === 0"
            @click="handleBatchDelete"
          >
            批量删除 ({{ selectedRows.length }})
          </el-button>
        </template>
      </DynamicTable>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import DynamicForm from "@/components/DynamicForm/index.vue";
import DynamicTable from "@/components/DynamicTable/index.vue";
import type { FormItemConfig } from "@/components/DynamicForm/types";
import type {
  TableColumn,
  PaginationConfig
} from "@/components/DynamicTable/types";

defineOptions({ name: "ScanTask" });

// 表单相关
const formRef = ref();
const isEdit = ref(false);
const editingId = ref<string | null>(null);

// 表单数据
const formData = ref({
  taskName: "",
  scanTarget: "",
  scanType: "port",
  scanStrategy: "default",
  scanPorts: "1-65535",
  scanDepth: 3,
  timeout: 30,
  concurrency: 100,
  enabled: true,
  scheduledTime: "",
  description: ""
});

// 表单配置
const formConfig: FormItemConfig[] = [
  {
    key: "taskName",
    name: "任务名称",
    type: "input",
    required: true,
    placeholder: "请输入任务名称",
    col: { md: 12, lg: 8 }
  },
  {
    key: "scanTarget",
    name: "扫描目标",
    type: "textarea",
    required: true,
    placeholder: "请输入扫描目标，支持IP、域名、IP段，每行一个",
    params: { rows: 3 },
    col: { md: 12, lg: 8 }
  },
  {
    key: "scanType",
    name: "扫描类型",
    type: "select",
    required: true,
    options: [
      { label: "端口扫描", value: "port" },
      { label: "服务扫描", value: "service" },
      { label: "漏洞扫描", value: "vulnerability" },
      { label: "Web扫描", value: "web" },
      { label: "综合扫描", value: "comprehensive" }
    ],
    col: { md: 6, lg: 4 }
  },
  {
    key: "scanStrategy",
    name: "扫描策略",
    type: "select",
    required: true,
    options: [
      { label: "默认策略", value: "default" },
      { label: "快速扫描", value: "fast" },
      { label: "深度扫描", value: "deep" },
      { label: "隐蔽扫描", value: "stealth" },
      { label: "自定义", value: "custom" }
    ],
    col: { md: 6, lg: 4 }
  },
  {
    key: "scanPorts",
    name: "扫描端口",
    type: "input",
    placeholder: "如：80,443,8080-8090",
    defaultValue: "1-65535",
    show: formData =>
      ["port", "service", "comprehensive"].includes(formData.scanType),
    col: { md: 8, lg: 6 }
  },
  {
    key: "scanDepth",
    name: "扫描深度",
    type: "number",
    defaultValue: 3,
    params: { min: 1, max: 10, step: 1 },
    col: { md: 4, lg: 3 }
  },
  {
    key: "timeout",
    name: "超时时间(秒)",
    type: "number",
    defaultValue: 30,
    params: { min: 5, max: 300, step: 5 },
    col: { md: 4, lg: 3 }
  },
  {
    key: "concurrency",
    name: "并发数",
    type: "number",
    defaultValue: 100,
    params: { min: 1, max: 1000, step: 10 },
    col: { md: 4, lg: 3 }
  },
  {
    key: "enabled",
    name: "启用任务",
    type: "switch",
    defaultValue: true,
    col: { md: 4, lg: 3 }
  },
  {
    key: "scheduledTime",
    name: "计划执行时间",
    type: "datetime",
    placeholder: "留空则立即执行",
    col: { md: 8, lg: 6 }
  },
  {
    key: "description",
    name: "任务描述",
    type: "textarea",
    placeholder: "请输入任务描述",
    params: { rows: 2 },
    col: { span: 24 }
  }
];

// 表格相关
const tableRef = ref();
const tableData = ref<any[]>([]);
const tableLoading = ref(false);
const selectedRows = ref<any[]>([]);

// 分页配置
const pagination = reactive<PaginationConfig>({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 表格列配置
const tableColumns: TableColumn[] = [
  {
    label: "任务名称",
    prop: "taskName",
    minWidth: 120,
    fixed: "left"
  },
  {
    label: "扫描目标",
    prop: "scanTarget",
    minWidth: 150,
    formatter: row => {
      const targets = row.scanTarget.split("\n").filter(Boolean);
      return targets.length > 1
        ? `${targets[0]} 等${targets.length}个目标`
        : targets[0];
    }
  },
  {
    label: "扫描类型",
    prop: "scanType",
    width: 100,
    slot: "scanType"
  },
  {
    label: "状态",
    prop: "status",
    width: 80,
    slot: "status"
  },
  {
    label: "进度",
    prop: "progress",
    width: 120,
    slot: "progress"
  },
  {
    label: "创建时间",
    prop: "createTime",
    width: 160,
    sortable: true
  },
  {
    label: "执行时间",
    prop: "executeTime",
    width: 160
  },
  {
    label: "完成时间",
    prop: "completeTime",
    width: 160
  },
  {
    label: "操作",
    prop: "action",
    width: 180,
    fixed: "right",
    slot: "action"
  }
];

// 状态相关方法
const getStatusTagType = (status: string) => {
  const statusMap: Record<string, string> = {
    pending: "info",
    running: "warning",
    completed: "success",
    failed: "danger",
    stopped: "info"
  };
  return statusMap[status] || "info";
};

const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    pending: "待执行",
    running: "运行中",
    completed: "已完成",
    failed: "失败",
    stopped: "已停止"
  };
  return statusMap[status] || "未知";
};

const getScanTypeText = (scanType: string) => {
  const typeMap: Record<string, string> = {
    port: "端口扫描",
    service: "服务扫描",
    vulnerability: "漏洞扫描",
    web: "Web扫描",
    comprehensive: "综合扫描"
  };
  return typeMap[scanType] || scanType;
};

// 表单提交
const handleSubmit = async () => {
  try {
    const valid = await formRef.value?.validate();
    if (!valid) return;

    // 这里应该调用API保存数据
    console.log("提交表单数据:", formData.value);

    if (isEdit.value) {
      // 更新现有任务
      const index = tableData.value.findIndex(
        item => item.id === editingId.value
      );
      if (index !== -1) {
        tableData.value[index] = {
          ...tableData.value[index],
          ...formData.value,
          updateTime: new Date().toLocaleString()
        };
      }
      ElMessage.success("任务更新成功！");
      cancelEdit();
    } else {
      // 创建新任务
      const newTask = {
        id: Date.now().toString(),
        ...formData.value,
        status: "pending",
        progress: 0,
        createTime: new Date().toLocaleString(),
        executeTime: "",
        completeTime: ""
      };
      tableData.value.unshift(newTask);
      pagination.total++;
      ElMessage.success("任务创建成功！");
      resetForm();
    }
  } catch (error) {
    ElMessage.error("操作失败，请重试！");
    console.error(error);
  }
};

// 重置表单
const resetForm = () => {
  formRef.value?.resetFields();
  formData.value = {
    taskName: "",
    scanTarget: "",
    scanType: "port",
    scanStrategy: "default",
    scanPorts: "1-65535",
    scanDepth: 3,
    timeout: 30,
    concurrency: 100,
    enabled: true,
    scheduledTime: "",
    description: ""
  };
};

// 取消编辑
const cancelEdit = () => {
  isEdit.value = false;
  editingId.value = null;
  resetForm();
};

// 编辑任务
const handleEdit = (row: any) => {
  isEdit.value = true;
  editingId.value = row.id;
  formData.value = { ...row };
};

// 执行任务
const handleExecute = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要执行任务 "${row.taskName}" 吗？`,
      "确认执行",
      { type: "warning" }
    );

    // 这里应该调用API执行任务
    console.log("执行任务:", row);

    // 模拟执行状态更新
    row.status = "running";
    row.executeTime = new Date().toLocaleString();
    row.progress = 10;

    ElMessage.success("任务开始执行！");

    // 模拟进度更新
    const interval = setInterval(() => {
      if (row.progress < 100) {
        row.progress += Math.random() * 20;
        if (row.progress >= 100) {
          row.progress = 100;
          row.status = "completed";
          row.completeTime = new Date().toLocaleString();
          clearInterval(interval);
          ElMessage.success(`任务 "${row.taskName}" 执行完成！`);
        }
      }
    }, 2000);
  } catch {
    // 用户取消
  }
};

// 删除任务
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除任务 "${row.taskName}" 吗？此操作不可恢复！`,
      "确认删除",
      { type: "warning" }
    );

    const index = tableData.value.findIndex(item => item.id === row.id);
    if (index !== -1) {
      tableData.value.splice(index, 1);
      pagination.total--;
      ElMessage.success("任务删除成功！");
    }
  } catch {
    // 用户取消
  }
};

// 批量删除
const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedRows.value.length} 个任务吗？此操作不可恢复！`,
      "确认批量删除",
      { type: "warning" }
    );

    const ids = selectedRows.value.map(row => row.id);
    tableData.value = tableData.value.filter(item => !ids.includes(item.id));
    pagination.total -= selectedRows.value.length;
    selectedRows.value = [];
    tableRef.value?.clearSelection();

    ElMessage.success("批量删除成功！");
  } catch {
    // 用户取消
  }
};

// 表格事件处理
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection;
};

const handlePageChange = (page: number) => {
  pagination.currentPage = page;
  loadTableData();
};

const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  loadTableData();
};

const refreshTable = () => {
  loadTableData();
};

// 加载表格数据
const loadTableData = async () => {
  tableLoading.value = true;
  try {
    // 这里应该调用API获取数据
    // 模拟数据
    if (tableData.value.length === 0) {
      const mockData = [
        {
          id: "1",
          taskName: "生产环境端口扫描",
          scanTarget: "192.168.1.1-192.168.1.100",
          scanType: "port",
          scanStrategy: "default",
          status: "completed",
          progress: 100,
          createTime: "2024-01-01 10:00:00",
          executeTime: "2024-01-01 10:05:00",
          completeTime: "2024-01-01 10:30:00"
        },
        {
          id: "2",
          taskName: "Web应用漏洞扫描",
          scanTarget: "https://example.com",
          scanType: "vulnerability",
          scanStrategy: "deep",
          status: "running",
          progress: 65,
          createTime: "2024-01-01 11:00:00",
          executeTime: "2024-01-01 11:05:00",
          completeTime: ""
        },
        {
          id: "3",
          taskName: "服务识别扫描",
          scanTarget: "10.0.0.1/24",
          scanType: "service",
          scanStrategy: "fast",
          status: "pending",
          progress: 0,
          createTime: "2024-01-01 12:00:00",
          executeTime: "",
          completeTime: ""
        }
      ];
      tableData.value = mockData;
      pagination.total = mockData.length;
    }
  } catch (error) {
    console.error("加载数据失败:", error);
    ElMessage.error("加载数据失败！");
  } finally {
    tableLoading.value = false;
  }
};

// 初始化
onMounted(() => {
  loadTableData();
});
</script>

<style scoped lang="scss">
.scan-task-container {
  padding: 20px;
  background-color: var(--el-bg-color);
  min-height: 100vh;

  .page-header {
    margin-bottom: 24px;

    h2 {
      margin: 0 0 8px 0;
      color: var(--el-text-color-primary);
      font-size: 24px;
      font-weight: 600;
    }

    p {
      margin: 0;
      color: var(--el-text-color-regular);
      font-size: 14px;
    }
  }

  .form-card {
    margin-bottom: 24px;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .card-actions {
        display: flex;
        gap: 8px;
      }
    }
  }

  .table-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .card-actions {
        display: flex;
        gap: 8px;
      }
    }
  }
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-card__header) {
  padding: 16px 20px;
  background-color: var(--el-fill-color-lighter);
  border-bottom: 1px solid var(--el-border-color-light);
}

:deep(.el-card__body) {
  padding: 24px;
}

:deep(.el-progress--line) {
  .el-progress-bar {
    padding-right: 0;
  }
}
</style>
